
package com.example.transaction.sys.service.impl;

import com.example.transaction.publisher.OrderExpirationPublisher;
import com.example.transaction.sys.controller.ItemController;
import com.example.transaction.sys.entity.Order;
import com.example.transaction.sys.mapper.ItemMapper;
import com.example.transaction.sys.mapper.OrderMapper;
import com.example.transaction.sys.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;


@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ItemController itemController;

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private OrderExpirationPublisher expirationPublisher;

    @Override
    public void findAndPublishExpiredOrders(LocalDateTime now) {
        List<Order> expiredOrders = orderMapper.findExpiredOrders(now, "待付款");
        for (Order order : expiredOrders) {
            // 计算延迟时间
            long delay = calculateDelay(order.getExpireTime(), now);
            expirationPublisher.publishOrderExpiration(order.getOrderID(), delay);
        }
    }

    @Override
    public void cancelOrder(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if (order != null && "待付款".equals(order.getOrderStatus())) {
            order.setOrderStatus("已取消");
            orderMapper.updateById(order);

            //清除缓存
            Cache ordersCache = cacheManager.getCache("orders");
            if (ordersCache != null) {
                ordersCache.clear();
            }

            //把商品状态重新置为可交易
            itemController.updateItemStatus(order.getItemID(),"可交易");
        }
    }

    private long calculateDelay(LocalDateTime expireTime, LocalDateTime now) {
        long delayMillis = expireTime.toInstant(ZoneOffset.UTC).toEpochMilli() - now.toInstant(ZoneOffset.UTC).toEpochMilli();
        // 确保延迟时间不是负数或零
        return delayMillis > 0 ? delayMillis : 1000; // 设置一个默认值或者处理逻辑
    }
}